<?php

class CategoryController extends AdminController {

    public $extension = null;

    const MODEL_CLASS_NAME = 'Category';

    public function init() {
	parent::init();
	$this->extension = isset($_GET['extension']) ? $_GET['extension'] : LGConstant::DEFAULT_CATEGORY_EXTENSION;
    }

    public function actionIndex() {

	$model = new Category(Category::SCENARIO_SEARCH);
	$model->controllerExtension = $this->extension;
	$model->unsetAttributes();  // clear any default values

	if (isset($_GET[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_GET[self::MODEL_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_GET[self::MODEL_CLASS_NAME]);
	} else if (isset($_POST[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_POST[self::MODEL_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_POST[self::MODEL_CLASS_NAME]);
	} else {
	    $modelState = Yii::app()->user->getState(app()->controller->id . self::MODEL_CLASS_NAME);
	    if ($modelState != null)
		$model->attributes = $modelState;
	}
	$this->render('index', array('model' => $model,));
    }

    public function actionRefresh() {
	Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, null);
	$this->redirect(url(app()->controller->id . "/index"));
    }

    function actions() {
	return array(
	    'create' => array(
		'class' => 'lib.components.actions.CreateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'messages' => array('success' => t('MSG_INFO_INSERT_SUCCESS', 'messages', array('{0}' => t('LBL_CATEGORY', 'category'))))
	    ),
	    'update' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'isRequiredAjax' => true,
		'view' => '_form',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_CATEGORY', 'category'))))
	    ),
	    'delete' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'customAction' => 'deleteCategory',
		'validateMethod' => 'validateDelete',
		'ajaxView' => "//share/_delete",
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_CATEGORY', 'category'))))
	    ),
	);
    }

    /**
     * Custumize delete action for delete category tree
     * @param array $model category array
     * @return \LGMessage
     */
    public function deleteCategory($model) {
	$isDeleted = true;
	$transaction = Category::model()->dbConnection->beginTransaction();
	for ($i = 0; $i < count($model); $i++) {
	    $m = $model[$i];

	    //Get all children of the $m node
	    //And check the children with $model items
	    //If a child is equal with a model item, remove the model item out list 
	    $list_child_category = Category::model()->getAllCategoryNodesHaveRootSpecifiedID($m->id, $m->extension);

	    foreach ($list_child_category as $data) {

		for ($j = $i; $j < count($model); $j++) {
		    $c = $model[$j];
		    if ($data->id == $c->id) {
			array_splice($model, $j, 1);
		    }
		}

		$category = new Category();
		$category->deleteByPk($data['id']);
	    }

	    $isDeleted = $m->delete();
	    if ($isDeleted == false)
		break;
	}

	// The model deleted successfully
	if ($isDeleted) {
	    $transaction->commit();

	    $msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_CATEGORY', 'category'))));

	    return $msg;
	}

	// Deletion was unsuccessful, set flash message
	else {
	    $transaction->rollback();
	    $msg = new LGMessage(MsgType::SUCCESS, t('THERE_WAS_AN_ERROR_WHILE_DELETING._PLEASE_TRY_AGAIN.', 'messages'));
	    return $msg;
	}
    }

    public function loadModel() {
	$model = null;
	if (isset($_GET['id'])) {
	    $ids = explode(',', $_GET['id']);
	    if (isset($ids)) {
		$criteria = new CDbCriteria;
		$criteria->addInCondition('id', $ids);
		$model = Category::model()->findAll($criteria);
	    }
	}
	return $model;
    }

    public function validateDelete($models) {
	$msg = NULL;
	$extension = isset($_REQUEST['catExtension']) ? $_REQUEST['catExtension'] : LGConstant::DEFAULT_CATEGORY_EXTENSION;
	foreach ($models as $category) {

	    if (!$category->CanDeleteCategory()) {
		$msg = new LGMessage(MsgType::ERROR, t('MSG_ERROR_DELETE_UNSUCCESS', 'messages'));
	    } else {
		//get childs of the parrent
		$list_child = Category::model()->getAllCategoryArrayHaveRootSpecifiedID($category->id, $extension);
		$listID = array();
		foreach ($list_child as $value) {
		    $listID[] = $value['id'];
		}
		if (Category::model()->isExistsOnArticle($listID)) {
		    $msg = new LGMessage(MsgType::ERROR, t('MSG_ERROR_DELETE_UNSUCCESS', 'messages'));
		}
	    }
	}
	return $msg;
    }

    public function actionActive($id) {
	if (Yii::app()->request->isAjaxRequest && ($id != '')) {
	    $category = Category::model()->findByPk($id);
	    $category->extension = $this->extension;
	    $category->scenario = Category::SCENARIO_UPDATE;

	    $newStatus = null;
	    if ($category->status == LGConstant::PUBLISH_STATUS) {
		$newStatus = LGConstant::UNPUBLISH_STATUS;
		$msgStatus = t('LBL_INACTIVED', 'category');
	    } else {
		$newStatus = LGConstant::PUBLISH_STATUS;
		$msgStatus = t('LBL_ACTIVED', 'category');
	    }

	    $isSuccess = $category->changeStatus($newStatus);

	    if ($isSuccess) {
		echo CJSON::encode(array(
		    'status' => MsgType::SUCCESS,
		    'content' => Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => t('LBL_CATEGORY', 'category'), '{1}' => $msgStatus))
		));
	    } else {
		if ($category->getError('status') != null) {
		    $msg = $category->getError('status');
		} else {
		    $msg = Yii::t('messages', 'MSG_NOT_ACTIVATED', array('{0}' => t('LBL_CATEGORY', 'category'), '{1}' => $msgStatus));
		}

		echo CJSON::encode(array(
		    'status' => MsgType::ERROR,
		    'content' => $msg)
		);
	    }
	    app()->end();
	}
    }
    
    /**
     * Swape 2 menu item. The items must be same parent_id together.
     * @param type $id
     * @param type $action
     * @throws InvalidArgumentException
     * @throws CHttpException
     * @author Kien Tran <kien.tran@logigear.com>
     */
    public function actionOrder($id, $action) {

      if ($id == NULL || $action == NULL) {
         throw new InvalidArgumentException();
      } else {
         $categoryFrom = Category::model()->findByPk($id);
         $categoryTo = Category::model()->findByPk($action);
         if ($categoryFrom == NULL || $categoryTo == NULL) {
            throw new CHttpException(404, Yii::t('messages', '404'));
         }

         //Check Are parent ids like together?
         if ($categoryFrom->parent_id != $categoryTo->parent_id) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }
         $temp = $categoryFrom->display_order;
         $categoryFrom->display_order = $categoryTo->display_order;
         $categoryTo->display_order = $temp;

         if (!$categoryFrom->saveAttributes(array('display_order'))) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }

         if (!$categoryTo->saveAttributes(array('display_order'))) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }
      }
   }

    public function getMenuDisplayName($category) {
	if ($category != NULL) {
	    $html = str_repeat('|---', $category->level);
	    $html = '<span class="indent">' . $html . '</span>';
	    $url = $this->createUrl("update", array("id" => $category->id));
	    $nameTag = Html::linkPopUpInGrid(
                    "linkEdit", 
                    $url,
                   CHtml::encode($category->name), 
                    "Edit Category", 
                    "update-dialog-open-link", "800","500");
	    //CHtml::link(CHtml::encode($category->name), $url);
	    $html .= $nameTag;

	    
	
	    return $html;
	}
	return '';
    }

      public function getHtmlUpButtonOfProductImage($menu) {

      $html = '';
      if ($menu->isUp != NULL) {
         $actionParam = '?action=' . $menu->isUp;
         $actionClassName = 'icon ' . LGConstant::ACTION_UP;

         $url = url(app()->controller->id . '/order/' . $menu->id . $actionParam);
	 $html .= $this->createAjaxButtonUpdateGridView( $actionClassName, $url);
      } else {
         $actionClassName = 'icon ' . LGConstant::ACTION_UP . ' disable';
         $html .= CHtml::button('', array(
                     'class' => $actionClassName,
         ));
      }

      return $html;
   }

   public function createAjaxButtonUpdateGridView ($className, $url) {
      return '<input class="'.$className.'" onclick="LGCMS.ajaxCallback(\''.$url.'\')" name="yt2" type="button">';
   }
   public function getHtmlDownButtonOfProductImage($category) {
      $html = '';
      if ($category->isDown != NULL) {
         $actionParam = '?action=' . $category->isDown;
         $actionClassName = 'icon ' . LGConstant::ACTION_DOWN;

	 $url = url( '/'.app()->controller->id . '/order/' . $category->id . $actionParam);
         $html .= $this->createAjaxButtonUpdateGridView( $actionClassName,$url);
      } else {
         $actionClassName = 'icon ' . LGConstant::ACTION_DOWN . ' disable';
         $html .= CHtml::button('', array(
                     'class' => $actionClassName,
         ));
      }

      return $html;
   }
}

?>